<template>
  <div class="params">
    <!-- 导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 主体区域 -->
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
      >
      </el-alert>
      <!-- 选择商品分类的区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader
            v-model="selectedCateList"
            :options="cateList"
            @change="handleChange"
            :props="cateProps"
            placeholder="请选择"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- 标签选项 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数模板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isbtnDisabled"
            @click="addAttrdialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template #default="scope">
                <el-tag
                  v-for="(i, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  >{{ i }}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="ID"></el-table-column>
            <el-table-column label="参数" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态参数 面板-->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isbtnDisabled"
            @click="addAttrdialogVisible = true"
            >添加属性</el-button
          >
          <!-- 静态参数表格 -->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template #default="scope">
                <el-tag
                  v-for="(i, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(i)"
                  >{{ i }}</el-tag
                >
                <!-- 可输入文本框 -->
                <el-input
                  v-if="scope.row.inputVisible"
                  ref="saveTagInput"
                  v-model="scope.row.inputValue"
                  class="input-new-tag"
                  size="mini"
                  @keyup.enter="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="ID"></el-table-column>
            <el-table-column label="参数" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数的对话框 -->
    <el-dialog
      v-model="addAttrdialogVisible"
      :title="'添加' + titleText"
      width="50%"
      @close="addDialogClosed"
    >
      <template #footer>
        <!-- 表单区域 -->
        <el-form
          ref="addFormRef"
          :model="addForm"
          label-width="15%"
          :rules="addFormRules"
        >
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>

        <span class="dialog-footer">
          <el-button @click="addAttrdialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addParams">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑参数的对话框 -->

    <el-dialog
      v-model="editAttrdialogVisible"
      :title="'修改' + titleText"
      width="50%"
      @close="editDialogClosed"
    >
      <template #footer>
        <!-- 表单区域 -->
        <el-form
          ref="editFormRef"
          :model="editForm"
          label-width="15%"
          :rules="editFormRules"
        >
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>

        <span class="dialog-footer">
          <el-button @click="editAttrdialogVisible = false">取消</el-button>
          <el-button type="primary" @click="editParams">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCateList,
  getParams,
  putParams,
  selectParamsById,
  changeParamsById,
  deleteParamsById,
} from "@/network/Goods.js";
export default {
  name: "Params",
  data() {
    return {
      cateList: [],
      addAttrdialogVisible: false,
      editAttrdialogVisible: false,
      cateProps: {
        //级联选择器的配置项
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      selectedCateList: [], //级联选择器的值
      activeName: "many", //被激活的页签名称

      manyTableData: [], //动态参数数据
      onlyTableData: [], //静态参数数据
      addForm: {
        attr_name: "",
      }, //表单数据
      editForm: {
        attr_name: "",
      }, //修改参数表单数据

      addFormRules: {
        attr_name: [
          { required: true, message: "请输入需要添加的项", trigger: "blur" },
        ],
      }, //表单验证规则
      editFormRules: {
        attr_name: [
          { required: true, message: "请输入需要修改的项", trigger: "blur" },
        ],
      }, //修改参数表单验证规则
    };
  },
  methods: {
    //加载数据列表
    async loadingCateList() {
      const { data: res } = await getCateList({});
      if (res.meta.status !== 200) {
        // console.log(res);
        return this.$message.error("获取数据列表失败");
      } else {
        this.cateList = res.data;
        // console.log(this.cateList);
      }
    },
    //联级选择器监听函数
    async handleChange() {
      //   console.log(this.selectedCateList);
      if (this.selectedCateList.length == 3) {
        this.getParamsData();
      } else {
        this.$message.error("只允许选择第三级分类");
        this.selectedCateList = [];
      }
    },

    // 获取参数
    async getParamsData() {
      const { data: res } = await getParams({
        id: this.cateId,
        params: {
          sel: this.activeName,
        },
      });

      if (res.meta.status != 200) {
        console.log(res);
        return this.$message.error("获取参数列表失败");
      } else {
        console.log(res.data);
        res.data.forEach((item, index) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
          item.inputVisible = false;
          item.inputValue = "";
          // console.log(res.data)
        }); //split函数将字符串以空格进行分割
        if (this.activeName === "many") {
          this.manyTableData = res.data;
        } else {
          this.onlyTableData = res.data;
        }
      }
      // console.log(this.manyTableData,this.onlyTableData)
    },

    // 监听添加对话框的关闭
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },

    // 提交添加的属性或参数
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        } else {
          const { data: res } = await putParams({
            id: this.cateId,
            data: {
              attr_name: this.addForm.attr_name,
              attr_sel: this.activeName,
            },
          });
          if (res.meta.status != 201) {
            console.log(res);
            return this.$message.error("添加失败");
          } else {
            this.$message.success("添加成功");
            this.getParamsData();
          }
        }
      });
      this.addAttrdialogVisible = false;
    },

    // 编辑参数按钮处理事件
    async showEditDialog(attr_id) {
      const { data: res } = await selectParamsById({
        id: this.cateId,
        attr_id: attr_id,
        params: {
          attr_sel: this.activeName,
        },
      });
      if (res.meta.status != 200) {
        // console.log(res, attr_id);
        return this.$message.error("获取参数信息失败");
      } else {
        console.log(res);
        this.editForm = res.data;
        this.editAttrdialogVisible = true;
      }
    },

    // 修改参数的对话框关闭时处理函数
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },

    // 确认修改参数并发送请求
    editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        } else {
          // console.log(this.activeName);
          const { data: res } = await changeParamsById({
            id: this.cateId,
            attrId: this.editForm.attr_id,
            data: {
              attr_name: this.editForm.attr_name,
              attr_sel: this.activeName,
            },
          });
          if (res.meta.status !== 200) {
            console.log(res);
            return this.$message.error("修改失败");
          } else {
            this.$message.success("修改成功");
            this.getParamsData();
          }
        }
      });
      this.editAttrdialogVisible = false;
    },

    //删除某一个属性
    async removeParams(id) {
      const { data: res } = await deleteParamsById({
        id: this.cateId,
        attrId: id,
      });
      if (res.meta.status != 200) {
        console.log(res);
        return this.$message.error("删除失败");
      } else {
        this.$message.success("删除成功");
        this.getParamsData();
      }
    },

    //Tag标签点击处理函数
    handleClick() {
      // console.log(this.activeName);
      this.getParamsData();
    },

    // 添加参数标签的显示和隐藏

    handleClose(tag) {
      
    },

    showInput(data) {
      data.inputVisible = true
      // this.$nextTick(() => {
      //   this.$refs.saveTagInput.$refs.input.focus()
      // })
    },

    handleInputConfirm(data) {
      // data.inputVisible = false;
      console.log(data)
    },
  },

  computed: {
    isbtnDisabled() {
      if (this.selectedCateList.length !== 3) {
        return true;
      } else {
        return false;
      }
    },

    //获取当前选中的三级分类的ID项
    cateId() {
      if (this.selectedCateList.length === 3) {
        return this.selectedCateList[2];
      } else {
        return null;
      }
    },

    //计算弹出框标题文本
    titleText() {
      if (this.activeName == "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    },
  },
  created() {
    this.loadingCateList();
  },
};
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}

.el-table {
  margin-top: 10px;
}

.el-tag {
  margin: 4px 10px;
}

.input-new-tag {
  width: 20vw;
}
</style>
